<template>
  <a-row :gutter="10">
    <a-col :md="6" :sm="24">
      <a-card :bordered="false">
        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 3px;">
          <a-button type="primary" @click="handleAddGroup(1)">创建分组</a-button>
           <a-dropdown>
            <a-button style="margin-left: 8px">
              更多操作 <a-icon type="down" />
            </a-button>
            <a-menu slot="overlay">
              <a-menu-item  v-if="this.currSelected&&!this.selectedLayer">
                <a type="primary" @click="handleAddGroup(3)">添加下级</a>
              </a-menu-item>
              <a-menu-item  v-if="this.currSelected&&!this.selectedLayer">
                <a type="primary" @click="handleAddLayer(1)">添加图层</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&!this.selectedLayer">
                <a type="primary" @click="handleAddGroup(2)">编辑</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&!this.selectedLayer">
                <a type="primary" @click="handleAddGroup(4)">查看</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&!this.selectedLayer">
                <a type="primary" @click="handleDelete()">删除</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&this.selectedLayer">
                <a type="primary"  @click="handleAddLayer(2)">编辑</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&this.selectedLayer">
                <a type="primary" @click="handleAddLayer(3)">查看</a>
              </a-menu-item>
              <a-menu-item v-if="this.currSelected&&this.selectedLayer">
                <a type="primary" @click="handleDelete()">删除</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </a-row>
        <div style="background: #fff; padding-left:16px; height: 100%; margin-top: 5px;">
          <a-alert type="info" :showIcon="true">
            <div slot="message">
              当前选择：<span v-if="this.currSelected">{{ getCurrSelectedTitle() }}</span>
              <a v-if="this.currSelected" style="margin-left: 10px;" @click="onClearSelected">取消选择</a>
            </div>
          </a-alert>
          <a-input-search @search="onSearch" style="width:100%; margin-top: 10px;" placeholder="请输入关键词" />
          <!-- 树 -->
          <a-col :md="11" :sm="24" class="department-tree">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none;">
                  <a-spin class="tree" :style="{ overflow: loading ? 'hidden' : 'auto' }" :spinning="loading">
                    <a-tree
                      :selectedKeys="selectedKeys"
                      :checkedKeys="checkedKeys"
                      :replaceFields="{title:'name', key: 'id', children:'childrenList'}"
                      :treeData="treeData"
                      :checkStrictly="checkStrictly"
                      :expandedKeys="iExpandedKeys"
                      showIcon
                      @expand="onExpand"
                      :autoExpandParent="autoExpandParent"
                      @select="onSelect">
                      <!-- <a-icon slot="layer" type="file" /> -->
                      <template slot="name" slot-scope="record">
                        <img
                          :src="getResourceURL(record)"
                          height="18px"
                          width="18px"
                        />
                        <span style="margin-left=3px">{{record.name}}</span>
                      </template>
                    </a-tree>
                    </a-spin>
                </span>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <a-col :md="18" :sm="24">
      <a-card v-if=" !selectedLayer || selectedKeys.length <= 0">
        <a-empty>
          <span slot="description"> 请先选择一个图层! </span>
        </a-empty>
      </a-card>
      <resources-list v-else ref="resourcesList"></resources-list>
    </a-col>
    <layer-resource-manage-modal ref="layerResourceManageModal" @ok="loadTree"></layer-resource-manage-modal>
    <layer-group-modal ref="layerGroupModal" @ok="loadTree"></layer-group-modal>
  </a-row>
</template>

<script>
import LayerResourceManageModal from './modules/BaseLayerResourceManageModal'

import ResourcesList from './modules/BaseResourcesList'
import LayerGroupModal from './modules/BaseLayerGroupModal'
import { deleteAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import tempIcon from '@assets/map/icon/icon-temp.png'
import fileIcon from '@assets/map/icon/file.png'

export default {
  name: 'BaseLayerResourceManage',
  components: {
    LayerResourceManageModal,
    LayerGroupModal,
    ResourcesList
  },
  mixins: [JeecgListMixin],
  props: {
    dictOptions: Object
  },
  data() {
    return {
      queryParam: {},
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      searchList: [],
      visible: false,
      rightClickSelectedKey: '',
      rightClickSelectedOrgCode: '',
      hiding: true,
      dropTrigger: '',
      depart: {},
      columns: [],
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      selectedLayer: false, // 判断选中的是否是图层
      autoIncr: 1,
      currSelected: {},
      allTreeKeys: [],
      checkStrictly: true,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      url: {
        list: '/subject/scSubjectResourceGroup/getGroupList',
        delete: '/subject/scSubjectResourceInfo/delete',
        deleteGroup: '/subject/scSubjectResourceGroup/delete',
        queryList: '/subject/scSubjectResourceGroup/queryByName',
        layerDetail: '/subject/scSubjectResourceInfo/queryById' // 查询图层详细信息
      },
      orgCategoryDisabled: false,
      actionData: {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        fixed: 'right',
        align: 'center',
        width: 200
      }
    }
  },
  computed: {
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
  },
  methods: {
    loadData() {
      this.refresh()
    },
    loadTree() {
      this.loading = true
      var that = this
      that.treeData = []
      getAction(this.url.list).then(res => {
        if (res.success) {
          this.allTreeKeys = []
          const record = res.result
          for (let i = 0; i < record.length; i++) {
            const temp = record[i]
            that.parseLayerInfoList(temp)
            that.treeData.push(temp)
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp)
          }
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getResourceURL(record) {
      var layerIcon = record.layerIcon || record.groupIcon
      return layerIcon ? `${window._CONFIG['domianURL']}/${layerIcon}` : record.isLayer ? tempIcon : fileIcon
    },
    parseLayerInfoList(node) {
      const list = node.resourceInfoList
      node.scopedSlots = { title: 'name' }
      if (list && list.length > 0) {
        for (let a = 0; a < list.length; a++) {
          const item = list[a]
          item.groupId = node.id
          item.isLayer = 1
          item.scopedSlots = { title: 'name' }
          item.name = item.resName
          node.childrenList.push(item)
        }
      }
      if (node.childrenList && node.childrenList.length > 0) {
        for (let a = 0; a < node.childrenList.length; a++) {
          this.parseLayerInfoList(node.childrenList[a])
        }
      }
    },
    setThisExpandedKeys(node) {
      if (node.childrenList && node.childrenList.length > 0) {
        this.iExpandedKeys.push(node.id)
        for (let a = 0; a < node.childrenList.length; a++) {
          this.setThisExpandedKeys(node.childrenList[a])
        }
      }
    },
    getAllKeys(node) {
      this.allTreeKeys.push(node.id)
      if (node.childrenList && node.childrenList.length > 0) {
        for (let a = 0; a < node.childrenList.length; a++) {
          this.getAllKeys(node.childrenList[a])
        }
      }
      if (node.resourceInfoList && node.resourceInfoList.length > 0) {
        for (let a = 0; a < node.resourceInfoList.length; a++) {
          this.getAllKeys(node.resourceInfoList[a])
        }
      }
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 获取图层详细信息，用来展示右侧搜索和表头
    getLayerDetail(id) {
      var that = this
      getAction(this.url.layerDetail, { id: id }).then(res => {
        if (res.success) {
          that.columns = []
          that.searchList = []
          this.currSelected = res.result
          if (this.currSelected && this.currSelected.resourceDetails) {
            for (const item of this.currSelected.resourceDetails) {
              if (item.isShowList) {
                const column = {
                  title: item.columnDesc,
                  align: 'center',
                  dataIndex: item.columnName
                }
                // 如果是图片，需要转换
                if (item.columnName === 'imgs') {
                  column.scopedSlots = { customRender: 'imgSlot' }
                }
                that.columns.push(column)
              }
              if (item.isQuery) {
                that.searchList.push(item)
              }
            }
          }
          that.columns.push(that.actionData)
          this.$refs.resourcesList.open(that.currSelected, that.columns, that.searchList)
        }
      })
    },
    refresh() {
      this.loadTree()
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    addRootNode() {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    onSearch(value) {
      const that = this
      if (value) {
        getAction(this.url.queryList, { name: value }).then(res => {
          if (res.success) {
            that.treeData = []
            const records = res.result
            for (let i = 0; i < records.length; i++) {
              const temp = records[i]
              that.parseLayerInfoList(temp)
              that.treeData.push(temp)
              that.setThisExpandedKeys(temp)
              that.getAllKeys(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {},
    hide() {
      this.visible = false
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      // this.checkedKeys = checkedKeys.checked
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
    },
    onSelect(selectedKeys, e) {
      this.hiding = false
      const record = e.node.dataRef
      if (record.isLayer) {
        // 代表是图层
        this.getLayerDetail(record.id)
        this.selectedLayer = true
      } else {
        this.selectedLayer = false
        this.currSelected = record
      }
      // this.model = this.currSelected
      this.selectedKeys = [record.id]
    },
    getCurrSelectedTitle() {
      return this.currSelected.name || this.currSelected.resName
    },
    onClearSelected() {
      this.hiding = true
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
      this.selectedLayer = false
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    handleAddGroup(num) {
      if (num == 1) {
        this.$refs.layerGroupModal.add()
        this.$refs.layerGroupModal.title = '新增分组'
        this.$refs.layerGroupModal.disableSubmit = false
      } else if (num == 2) {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中分组！')
          return false
        }
        this.$refs.layerGroupModal.disableSubmit = false
        this.$refs.layerGroupModal.edit(this.currSelected)
        this.$refs.layerGroupModal.title = '编辑分组'
      } else if (num == 3) {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中分组！')
          return false
        }
        this.$refs.layerGroupModal.add(this.currSelected)
        this.$refs.layerGroupModal.title = '添加下级'
        this.$refs.layerGroupModal.disableSubmit = false
      } else {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中分组！')
          return false
        }
        this.$refs.layerGroupModal.disableSubmit = true
        this.$refs.layerGroupModal.edit(this.currSelected)
        this.$refs.layerGroupModal.title = '分组详情'
      }
    },
    handleAddLayer(num) {
      if (num == 1) {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中分组！')
          return false
        }
        this.$refs.layerResourceManageModal.add()
        this.$refs.layerResourceManageModal.disableSubmit = false
        this.$refs.layerResourceManageModal.currSelected = this.currSelected
        this.$refs.layerResourceManageModal.title = '新增图层'
      } else if (num == 2) {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中图层！')
          return false
        }
        this.$refs.layerResourceManageModal.disableSubmit = false
        this.$refs.layerResourceManageModal.edit(this.currSelected)
        this.$refs.layerResourceManageModal.title = '编辑图层'
      } else {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中图层！')
          return false
        }
        this.$refs.layerResourceManageModal.disableSubmit = true
        this.$refs.layerResourceManageModal.edit(this.currSelected)
        this.$refs.layerResourceManageModal.title = '图层详情'
      }
    },
    handleDelete() {
      var that = this
      const key = this.currSelected.id
      if (!key) {
        this.$message.warning('请先选中删除的内容！')
        return false
      }
      const url = this.selectedLayer ? that.url.delete : that.url.deleteGroup
      this.$confirm({
        title: '确认删除',
        content: '确定要删除么?',
        onOk: function() {
          deleteAction(url, { id: key }).then(resp => {
            if (resp.success) {
              // 删除成功后，去除已选中中的数据
              that.checkedKeys.splice(
                that.checkedKeys.findIndex(key => key === that.rightClickSelectedKey),
                1
              )
              that.$message.success('删除成功!')
              that.loadTree()
              that.onClearSelected()
            } else {
              that.$message.warning('删除失败!')
            }
          })
        }
      })
    },

    // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      // this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-body .table-operator {
  margin: 15px;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0;
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

#app .desktop {
  height: auto !important;
}

/** Button按钮间距 */
.ant-btn {
  margin-left: 3px;
}

.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

.department-tree {
  margin-top: 5px;
  width: 100%;
  height: 495px;
  overflow: auto;
  ::v-deep .ant-spin-nested-loading {
    position: initial;
  }
}

.basicInfo-card {
  ::v-deep .ant-card-body {
    height: 650px;
    overflow: auto;
  }
}

.tree {
  height: calc(100% - 4px);
  margin: 2px 0;
}
</style>
